<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;

class TcpClient extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('start_tcp_client')
            ->setDescription('the app\command\tcpclient command')
            ->addArgument('param', Argument::OPTIONAL, 'param');
    }

    protected function execute(Input $input, Output $output)
    {
        $param = $input->getArgument('param');
        $param = base64_decode($param);

        $param = json_decode($param, true);
        //$param = ['serial_number' => 'SL20221122009', 'command' => '01 06 00 0C 00 01 88 09'];

        $serial_number = $param['serial_number'] ?? '';
        $command = $param['command'] ?? '';
        if (!$serial_number || !$command) {
            $output->write('[客户端]传入参数为空!');
            return false;
        }

        $redis = Cache::store('redis');
        $client_info = json_decode($redis->get("clientInfo:{$serial_number}") ?? '', true) ?? [];
        if (!$client_info) {
            $output->write('[客户端]获取client info信息为空');
            return false;
        }

        $server_fd = $client_info['fd'] ?? '';

        $data = [
            'fd' => $server_fd,
            'command' => $command,
            'serial_number' => $serial_number,
        ];

        $client = new \Swoole\Client(SWOOLE_SOCK_TCP);
        if (!$client->connect('127.0.0.1', 9602, 0.5)) {
            $output->write('[客户端]客户端连接失败!');
            Log::record('[error]tcp客户端连接失败!' . var_export($param, true), 'debug');
            return false;
        }

        $client->send(json_encode($data, 320));
        $recv = $client->recv();
        if ($recv) $output->write('指令已发送!');
        $client->close();
    }
}
